import { getCurrentTimeParam } from "./globalTimeFilter.js";
import { API_CONFIG } from "./config.js";

document.addEventListener("DOMContentLoaded", function () {
  // 获取客服排行容器
  const jiageElement = document.getElementById("jiage");
  if (!jiageElement) return;

  // 创建新的客服排行结构
  jiageElement.innerHTML = `
        <div class="staff-ranking-container">
            <div class="ranking-header">
                <div class="ranking-indicators">
                    <div class="indicator active" data-type="voice"></div>
                    <div class="indicator" data-type="text"></div>
                </div>
            </div>
            
            <div class="ranking-type">语音接待排行</div>
            
            <div class="ranking-content voice-ranking active">
                <table>
                    <thead>
                        <tr>
                            <th>排名</th>
                            <th>客服ID</th>
                            <th>接待量</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr><td colspan="3" class="loading-data">数据加载中...</td></tr>
                    </tbody>
                </table>
            </div>
            
            <div class="ranking-content text-ranking">
                <table>
                    <thead>
                        <tr>
                            <th>排名</th>
                            <th>客服ID</th>
                            <th>接待量</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr><td colspan="3" class="loading-data">数据加载中...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    `;

  // 添加样式
  const style = document.createElement("style");
  style.innerHTML = `
        .staff-ranking-container {
            padding: 15px;
            // background: rgba(6, 33, 68, 0.7);
            border-radius: 8px;
            border: 1px solid rgba(36, 187, 236, 0.2);
            height: 100%;
            position: relative;
        }
        
        .ranking-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .ranking-title {
            font-size: 2rem;
            font-weight: 600;
            color: #24bbec;
            position: relative;
        }
        
        .ranking-title::after {
            content: '';
            position: absolute;
            bottom: -5px;
            left: 0;
            width: 100%;
            height: 3px;
            background: linear-gradient(90deg, #24bbec, transparent);
            border-radius: 3px;
        }
        
        .ranking-indicators {
            display: flex;
            gap: 10px;
        }
        
        .indicator {
            width: 14px;
            height: 14px;
            border-radius: 50%;
            // background: rgba(162, 211, 232, 0.3);
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .indicator.active {
            background: #24bbec;
            transform: scale(1.2);
        }
        
        .ranking-type {
            text-align: center;
            font-size: 2rem;
            margin: 0 auto 15px;
            background: rgba(10, 58, 124, 0.4);
            padding: 8px 15px;
            border-radius: 20px;
            display: inline-block;
            color: #e6f7ff;
            border: 1px solid rgba(36, 187, 236, 0.2);
        }
        
        .ranking-content {
            overflow-y: auto;
            border-radius: 6px;
            background: rgba(10, 58, 124, 0.3);
            border: 1px solid rgba(36, 187, 236, 0.15);
            display: none;
        }
        
        .ranking-content.active {
            display: block;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        thead {
            background: rgba(29, 111, 160, 0.3);
            position: sticky;
            top: 0;
        }
        
        th {
            padding: 12px 10px;
            text-align: center;
            color: #a2d3e8;
            font-weight: 500;
            font-size: 2rem;
            border-bottom: 1px solid rgba(36, 187, 236, 0.2);
        }
        
        tbody tr {
            transition: all 0.3s ease;
        }
        
        tbody tr:hover {
            background: rgba(36, 187, 236, 0.2);
        }
        
        td {
            padding: 12px 10px;
            text-align: center;
            color: #e6f7ff;
            border-bottom: 1px solid rgba(36, 187, 236, 0.1);
        }
        
        .medal-icon {
            display: inline-block;
            width: 24px;
            height: 24px;
            font-size: 1.2rem;
            line-height: 24px;
            text-align: center;
            border-radius: 50%;
            font-weight: bold;
            margin-right: 8px;
        }
        
        .medal-1 {
            background: radial-gradient(circle at 30% 30%, #FFD700, #FF9800);
            color: #a60000;
        }
        
        .medal-2 {
            background: radial-gradient(circle at 30% 30%, #C0C0C0, #808080);
            color: #333;
        }
        
        .medal-3 {
            background: radial-gradient(circle at 30% 30%, #CD7F32, #8C5400);
            color: #fff;
        }
        
        .ranking-content::-webkit-scrollbar {
            width: 6px;
        }
        
        .ranking-content::-webkit-scrollbar-thumb {
            background-color: #24bbec;
            border-radius: 3px;
        }
    `;
  document.head.appendChild(style);

  // 生成排行榜数据
  generateRankings();

  // 设置排行榜切换
  setupRankingSwitch();
});

// 生成排行榜数据
function generateRankings() {
  let timeParam = getCurrentTimeParam();

  // 改进时间格式转换：确保格式为 YYYY-MM-DD（两位数月份和日期）
  if (timeParam) {
    const parts = timeParam.split("-");
    if (parts.length >= 3) {
      const year = parts[0].length === 2 ? "20" + parts[0] : parts[0];
      const month = parts[1].padStart(2, "0");
      const day = parts[2].padStart(2, "0");
      timeParam = `${year}-${month}-${day}`;
    }
  }

  // 定义不同排行的API配置
  const apiConfig = {
    voice: {
      id: "0e6138255ca044c1b0dbb1dessdgsegc", // 语音接待ID
      type: "2", // 语音接待type值
    },
    text: {
      id: "0e6138255ca044c1b0dbb1de9817f28d", // 文字接待ID
      type: "1", // 文字接待type值
    }
  };

  // 获取语音接待排行数据
  const voicePromise = axios.get(`${API_CONFIG.BASE_URL}/api/metrics/${apiConfig.voice.id}/single-metrics-value`, {
    params: {
      time: getCurrentTimeParam(),
      type: apiConfig.voice.type
    }
  })
      .then(response => {
        console.log("语音排行API响应:", response);
        if (response.data && response.data.code === "00000") {
          const data = response.data.data;

          // 过滤掉id6d为"0"的数据
          const filteredData = data.filter(item => item.id6d !== "0");

          // 将语音接待数据转换为排行榜格式
          return filteredData.map(item => ({
            id: item.id6d || "未知ID", // 使用 id6d 字段作为客服ID
            count: parseInt(item.worker_call_reception_count) || 0
          }));
        }
        return [];
      })
      .catch(error => {
        console.error("获取语音接待排行失败:", error);
        return [];
      });

  // 获取文字接待排行数据
  const textPromise = axios.get(`${API_CONFIG.BASE_URL}/api/metrics/${apiConfig.text.id}/single-metrics-value`, {
    params: {
      time: "2021",
      type: apiConfig.text.type
    }
  })
      .then(response => {
        if (response.data && response.data.code === "00000") {
          const data = response.data.data;

          // 过滤掉id6d为"0"的数据
          const filteredData = data.filter(item => item.id6d !== "0");

          // 将文字接待数据转换为排行榜格式
          return filteredData.map(item => ({
            id: item.id6d || "未知ID", // 使用 id6d 字段作为客服ID
            count: parseInt(item.worker_text_reception_count) || 0
          }));
        }
        return [];
      })
      .catch(error => {
        console.error("获取文字接待排行失败:", error);
        return [];
      });

  // 处理所有排行数据
  Promise.all([voicePromise, textPromise])
      .then(([voiceData, textData]) => {
        // 填充语音接待排行榜
        updateRankingTable('.voice-ranking', voiceData);

        // 填充文字接待排行榜
        updateRankingTable('.text-ranking', textData);
      })
      .catch(error => {
        console.error("生成排行榜数据失败:", error);
        showErrorInTables();
      });
}

// 更新排行榜表格
function updateRankingTable(selector, data) {
  const tbody = document.querySelector(`${selector} tbody`);
  tbody.innerHTML = "";

  if (data.length === 0) {
    tbody.innerHTML = `<tr><td colspan="3" class="no-data">暂无数据</td></tr>`;
    return;
  }

  // 对数据排序（高→低）
  data.sort((a, b) => b.count - a.count);

  data.forEach((staff, index) => {
    const tr = document.createElement("tr");
    let medalClass = "";
    let medalHTML = "";

    if (index < 3) {
      medalClass = `medal-${index + 1}`;
      medalHTML = `<span class="medal-icon ${medalClass}">${index + 1}</span>`;
    }

    tr.innerHTML = `
      <td>${medalHTML} ${index + 1}</td>
      <td>${staff.id}</td>
      <td>${staff.count}</td>
    `;

    // 突出前三名
    if (index < 3) {
      tr.style.background = 'rgba(36, 187, 236, 0.08)';
    }

    tbody.appendChild(tr);
  });
}

// 显示错误信息
function showErrorInTables() {
  const errorHTML = `<tr><td colspan="3" class="error-data">数据加载失败，请稍后重试</td></tr>`;

  document.querySelector('.voice-ranking tbody').innerHTML = errorHTML;
  document.querySelector('.text-ranking tbody').innerHTML = errorHTML;
}

// 监听时间变化事件
document.addEventListener("timePeriodChanged", function (event) {
  generateRankings();
});

// 设置排行榜切换
function setupRankingSwitch() {
  const types = [
    {
      element: document.querySelector(".voice-ranking"),
      name: "语音接待排行",
      type: "voice",
    },
    {
      element: document.querySelector(".text-ranking"),
      name: "文字接待排行",
      type: "text",
    }
  ];

  const indicators = document.querySelectorAll(".indicator");
  const typeTitle = document.querySelector(".ranking-type");

  // 初始状态显示语音接待排行
  let currentIndex = 0;
  types[currentIndex].element.classList.add("active");
  typeTitle.textContent = types[currentIndex].name;
  indicators[currentIndex].classList.add("active");

  // 设置切换定时器
  let switchInterval = setInterval(() => {
    // 移除当前活跃状态
    types[currentIndex].element.classList.remove("active");
    indicators[currentIndex].classList.remove("active");

    // 移动到下一个
    currentIndex = (currentIndex + 1) % types.length;

    // 设置新活跃状态
    types[currentIndex].element.classList.add("active");
    typeTitle.textContent = types[currentIndex].name;
    indicators[currentIndex].classList.add("active");

    // 动画效果
    animateRankingSwitch(typeTitle);
  }, 5000);

  // 添加指示器点击事件
  indicators.forEach((indicator, index) => {
    indicator.addEventListener("click", () => {
      // 清除自动切换
      clearInterval(switchInterval);

      // 移除当前活跃状态
      types[currentIndex].element.classList.remove("active");
      indicators[currentIndex].classList.remove("active");

      // 设置新活跃状态
      currentIndex = index;
      types[currentIndex].element.classList.add("active");
      typeTitle.textContent = types[currentIndex].name;
      indicators[currentIndex].classList.add("active");

      // 重新启动自动切换
      switchInterval = setInterval(() => {
        types[currentIndex].element.classList.remove("active");
        indicators[currentIndex].classList.remove("active");

        currentIndex = (currentIndex + 1) % types.length;

        types[currentIndex].element.classList.add("active");
        typeTitle.textContent = types[currentIndex].name;
        indicators[currentIndex].classList.add("active");

        animateRankingSwitch(typeTitle);
      }, 5000);
    });
  });
}

// 切换动画效果
function animateRankingSwitch(element) {
  element.style.animation = "none";
  setTimeout(() => {
    element.style.animation = "fadeScale 0.5s ease";
  }, 10);

  // 添加动画样式
  const style = document.createElement("style");
  style.innerHTML = `
        @keyframes fadeScale {
            0% { 
                opacity: 0; 
                transform: scale(0.8); 
            }
            100% { 
                opacity: 1; 
                transform: scale(1); 
            }
        }
    `;
  document.head.appendChild(style);

  // 移除临时样式
  setTimeout(() => {
    document.head.removeChild(style);
  }, 500);
}
